package cn.miju.ser.framework.exception;

import cn.miju.common.content.CodeMessage;
import cn.miju.common.exception.ValidateException;
import cn.miju.ser.framework.response.MiJuPayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;

/**
 * <pre>
 * 统一异常处理
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-01 15:23
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public MiJuPayResponse exceptionHandler(Exception e) {
        if (e instanceof ApiException) {
            //业务异常
            return MiJuPayResponse.fail(CodeMessage.FAIL.getCode(), e.getMessage());
        } else if (e instanceof BindException) {
            //接口参数校验异常
            BindingResult bindingResult;
            if (e instanceof MethodArgumentNotValidException) {
                bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            } else {
                bindingResult = ((BindException) e).getBindingResult();
            }
            StringJoiner stringJoiner = new StringJoiner("，","【", "】");
            if (bindingResult.hasFieldErrors()) {
                bindingResult.getFieldErrors().forEach(fieldError -> {
                    stringJoiner.add(fieldError.getDefaultMessage());
                });
            }
            if (stringJoiner.length() > 0) {
                return MiJuPayResponse.fail(CodeMessage.VALIDATE_FAIL.getCode(), stringJoiner.toString());
            }
            return MiJuPayResponse.fail(CodeMessage.VALIDATE_FAIL.getCode(), e.getMessage());
        } else if (e instanceof ValidateException) {
            //手动参数校验异常
            return MiJuPayResponse.fail(CodeMessage.VALIDATE_FAIL.getCode(), e.getMessage());
        }
        log.error("未知异常！", e);
        return MiJuPayResponse.fail(CodeMessage.FAIL.getCode(), "系统异常，请联系管理员！");
    }

}
